<?php

class Engine_Resource_Locale extends Zend_Application_Resource_ResourceAbstract {

	protected $_translate;
	
	public function init() {
		return $this->getLocale();
	}
	
	public function getLocale() {
   	
    	$session = new Zend_Session_Namespace();
    	if (isset($session->language)) {
    		$lang = $session->language;
    	} else {
    		$options = $this->getOptions();
    		if (isset($options['language']))
				$lang = $options['language'];  
    	}	
    	if (!isset($lang))
    		$lang = 'en';
 		
    	$session->language = $lang;
    		
    	$folder = APPLICATION_PATH . "/language/$lang";
    	if (file_exists($folder)) {

			Zend_Translate::setCache(Zend_Registry::get('Zend_Cache'));
   			$this->_translate = new Zend_Translate(array('adapter' => 'csv', 
   														'content' => ($folder."/engine.csv"), 
   														'locale' => $lang,
   														'delimiter' => '^')
   			);
   			if ($handle = opendir($folder)) {
   				while (false !== ($file = readdir($handle))) {
   					$parts = pathinfo($file);
   					if (($parts['extension'] == 'csv') && ($file != 'engine.csv')) {
   						$file = $folder.'/'.$file;
   						$this->_translate->addTranslation($file, $lang);
   					}
   				}
   			}
   			Zend_Registry::set('Zend_Translate', $this->_translate);

	    	if (strlen($lang) > 4) {
    			$lang = str_replace('-', '_', $lang);
    			$lang = substr($lang,0,3) . strtoupper(substr($lang,3, 2));
    		} 
    		
    		
    		$locale = new Zend_Locale();
    		$locale->setLocale($lang);
			Zend_Registry::set('Zend_Locale', $locale);

    		try {
				$currency = new Zend_Currency($locale->getRegion() );
			} catch (Exception $e) {
				$currency = new Zend_Currency('US');
			}
			Zend_Registry::set('Zend_Currency', $currency);
			
    		Zend_Locale::setCache(Zend_Registry::get('Zend_Cache'));
    	}
    	
    	return $this->_translate;
    }
    
}
?>